#!/bin/bash
#
# stressbuild - test many different build configurations at once
#

typeset -i count
typeset -i mincount

machines="tz corvette wcs funhouse t2 afm bop tester"
sim_options="n y"
gcc_options="4.3.4"
debugger_options="y n"
bpt_options="y n"
mincount=1
make_options="-j3"

while [ "x$1" != "x" ]; do
option=$1; shift
case $option in
	--loop)
		sim_options="$sim_options $sim_options $sim_options $sim_options $sim_options"
		;;
	--sim)
		sim_options="y"
		;;
	--6809)
		sim_options="n"
		;;
	--debug)
		debugger_options="y"
		;;
	--nodebug)
		debugger_options="n"
		;;
	--bpt)
		bpt_options="y"
		;;
	--nobpt)
		bpt_options="n"
		;;
	--sys*)
		machines="tester"
		;;
	--fast)
		machines="funhouse t2 tz wcs afm"
		sim_options="n"
		debugger_options="y"
		gcc_options="4.3.4"
		;;
	--gcc)
		gcc_options="$1"; shift
		;;
	[a-z]*)
		machines="$option"
		;;
	[0-9]*)
		mincount="$option"
		;;
	*)
		echo "Unknown option $option"
		exit 1
		;;
esac
done

count=0
rm -f stressbuild.log
for sim in $sim_options; do
	if [ "$sim" = "y" ]; then
		CONFIG_SIM=y
	else
		unset CONFIG_SIM
	fi
	for bpt in $bpt_options; do
	if [ "$bpt" = "y" ]; then
		CONFIG_BPT=y
	else
		unset CONFIG_BPT
	fi
	for mach in ${machines}; do
		for debugger in $debugger_options; do
			if [ "$sim" = "n" ]; then
				gcctargets=${gcc_options}
			else
				gcctargets=`echo nop`;
			fi
			for gcc in $gcctargets; do
				if [ "$gcc" = "nop" ]; then gcc=; fi
				count=$(($count + 1))
				if [ "$count" -lt "$mincount" ]; then continue; fi
				for target in `echo clean default_target`; do

					cfg="CONFIG_SIM=$CONFIG_SIM MACHINE=$mach FREEWPC_DEBUGGER=$debugger CONFIG_BPT=$bpt GCC_VERSION=$gcc target=$target"
					echo "Begin: ($count) $cfg" | tee -a stressbuild.log

					export MACHINE=$mach
					export FREEWPC_DEBUGGER=$debugger
					export GCC_VERSION=$gcc
					export CONFIG_SIM
					export CONFIG_BPT
					make $make_options DOTCONFIG="" $target 2>&1 > /dev/null
					rc="$?"

					if [ -f err ]; then
						echo "Error file:" | tee -a stressbuild.log
						cat err | tee -a stressbuild.log
					fi

					echo "End: ($count) $cfg" | tee -a stressbuild.log
					echo "Exit code: ($count) $rc" | tee -a stressbuild.log
					echo "" | tee -a stressbuild.log
					if [ "$rc" != "0" ]; then
						exit $rc
					fi
				done
			done
		done
	done
done
done
echo "All done".
exit 0
